import {
  createReadStream,
  createWriteStream,
} from 'node:fs';

import {
  pipeline,
} from 'node:stream';

import {
  scrypt,
  randomFill,
  createCipheriv,
} from 'node:crypto';

import { createInterface } from 'node:readline';

const algorithm = 'aes-256-cbc';
let password = 'Password used to generate key';

const rl = createInterface({
  input: process.stdin,
  output: process.stdout
});
rl.question('请输入：', (answer) => {
      password = answer.trim();
      encrypto();
      rl.close();
    });
    
async function encrypto(){
    console.log("开始加密："+ process.argv[2]);
    
    const fname = process.argv[2];

    // First, we'll generate the key. The key length is dependent on the algorithm.
    // In this case for aes256, it is 32 bytes (256 bits).
    //let num=0;
    scrypt(password, 'salthell', 32, (err, key) => {
      if (err) throw err;
      // Then, we'll generate a random initialization vector
      randomFill(new Uint8Array(16), (err, iv) => {
        if (err) throw err;

        const cipher = createCipheriv(algorithm, key, iv);
        //console.log(`number: ${num}`);
        
        const input = createReadStream(fname);
        const output = createWriteStream(fname+'.enc');
        output.write(iv);
        //console.log(iv.toHex());

        pipeline(input, cipher, output, (err) => {
          if (err) throw err;
        });
      });
    });

}

